<!DOCTYPE html>

<html>
	<head>
		<meta charset="utf-8" />
		<link rel="stylesheet" type="text/css" href="style.css" />
		<title>Topic</title>
	</head>

	<body>
	
		<?php

            session_start();

			if (isset($_GET['idCat']))
				{
 					$idCat = $_GET['idCat'];
 					if (isset($_GET['page']))
 						{
 							$page = $_GET['page'];
						}
					else 
						{
							$page = 1;
						}
				}
			else 
				{
					?>

						<script type="text/JavaScript">
							document.location.href="index.php";
						</script>									
					
					<?php
				}

			$mysqli = new mysqli("localhost", "root", "root", "forum");
			
			/* Vérification de la connexion */
			if (mysqli_connect_errno())
				{
    				echo 'Échec de la connexion : ' . mysqli_error();
    				exit;
				}

			$requete = 'SELECT * FROM sujet WHERE id_cat = \'' . $idCat . '\';';
			if ($response = $mysqli->query($requete))
				{
					$cpt = 0;
					while ($row = $response->fetch_assoc())    
						{
							$arrayToAff[$cpt] = $row;
							$cpt++;
						}
					$maxPage = ($cpt / 20) + 1;
					$cpt = 0;
					$toAffMin = ($page - 1) * 20;
					$toAffMax = ($page * 20) - 1;
					$toAff = $toAffMin;
					while (isset($arrayToAff[$toAff]) && $arrayToAff[$toAff] != null && $cpt < 20)
						{
							echo '<div class="core-design"><a href="affPost.php?idSuj=' . $arrayToAff[$toAff]["id_sujet"] . '"<p> Title : ' . $arrayToAff[$toAff]['titre_sujet'] . '</p></a>';
                            if (isset($_SESSION) && isset($_SESSION['connected']) && $_SESSION['connected'] == true && ($_SESSION['isAdmin'] || $_SESSION['isModo']))
								{
									echo '<div class="delete-topic"><a href="delete_topic.php?sujet=' . $arrayToAff[$toAff]["id_sujet"] . '">Supprimer le topic</a></div>';	
                                }
                            echo '</div>';
							$cpt++;
							$toAff++;
						}
					$cpt = 1;

				
					echo '<div class="core-design"><form action="putTopic.php?idCat=' . $idCat . '" method="post">
							<p>Titre : <input type="text" name="titre" /></p>
							<p><input type="submit" value="OK"></p>
							</form></div>';					
					
					echo '<footer>Page' . $page . ' / ' . intval($maxPage) . ' ';
					while ($cpt < $maxPage)
					{
						echo '<a href="affTopic.php?page=' . $cpt . '&idCat=' . $idCat . '">' . $cpt . ' </a>';
						$cpt++;
					}
					echo '</footer>';
				}
			else 
				{
					?>

						<script type="text/JavaScript">
							document.location.href="index.php";
						</script>									
					
					<?php
				}
		
		?>
	</body>
</html>